import os
try:
    import gradio as gr
except ImportError:
    print("Gradio 库未安装，正在安装...")
    os.system("pip install gradio -i https://pypi.tuna.tsinghua.edu.cn/simple/")
    import gradio as gr

try:
    import requests
except ImportError:
    print("requests 库未安装，正在安装...")
    os.system("pip install requests -i https://pypi.tuna.tsinghua.edu.cn/simple/")
    import requests




# 函数：检查多个 Docker 镜像源的可用性
def check_docker_registry(urls):
    success_results = []  # 存储成功访问镜像源的地址
    failure_results = []  # 存储无法访问镜像源的地址
    url_list = urls.split("\n")
    for url in url_list:
        url = url.strip()
        if not url:
            continue
        try:
            response = requests.get(url, timeout=5)
            if response.status_code == 200:
                success_results.append(url)
            else:
                failure_results.append(url)
        except requests.exceptions.RequestException:
            failure_results.append(url)

    success_message = "以下镜像源地址可访问：\n\n" + "\n".join(success_results)
    failure_message = "以下镜像源地址不可访问：\n\n" + "\n".join(failure_results)
    return success_message + "\n\n" + failure_message

if __name__ == '__main__':
    # 使用 Gradio 创建 Web 界面
    with gr.Blocks(title="Docker 镜像源检查器", theme="default") as demo:
        gr.Markdown("## Docker 镜像源检查器")
        with gr.Row():
            url_input = gr.Textbox(label="Docker 镜像源 URL (以换行符分隔)", lines=10, placeholder="输入每个 URL，并以换行符分隔")
        result_output = gr.Textbox(label="结果", interactive=False, lines=20)
        check_button = gr.Button("检查")
        # 按钮点击事件绑定到检查函数
        check_button.click(fn=check_docker_registry, inputs=url_input, outputs=result_output)
    # 启动 Gradio 应用
    demo.launch(server_name="127.0.0.1", server_port=5000)
